// 作品选择窗口
import bindAll from 'lodash.bindall';
import PropTypes from 'prop-types';
import React from 'react';
import classNames from 'classnames';
import Spinner from '../components/spinner/spinner.jsx';
import {Card} from 'antd';
const {Meta} = Card;

import Modal from './modal.jsx'; // 选择窗口组件
import {getYxProjectLibrary} from '../session-api';
import styles from './project-library.css';

class ProjectLibrary_yx extends React.Component {
    constructor (props) {
        super(props);
        bindAll(this, [
            'handleClose',
            'handleOnScroll',
            'handleItemSelect',
            'setFilteredDataRef',
            'handleGetMoreItem'
        ]);
        this.state = {
            projects: [], // projects.length 已获取的作品数，用于流方式加载
            isOver: false, // 是否已获取了分类下的全部作品
            loading: true // 是否已加载完
        };
    }
    componentWillMount (){
        this.getItemList(true); // 加载完后，第一次获取作品列表
    }
    // 获取作品列表
    getItemList (newProjects) {
        if (this.state.isOver) {
            return;
        }
        
        const searchParam = `l=${this.state.projects.length}&n=20`;
        getYxProjectLibrary(searchParam).then(res => {
            this.setState({loading: false}); 

            if (res.data.length < 20) {
                this.setState({isOver: true});
            }

            if (newProjects){
                this.setState({projects: res.data});
            } else {
                this.setState({projects: this.state.projects.concat(res.data)});
            }
        });
    }
    
    // 关闭窗口
    handleClose () {
        this.props.onRequestClose();
    }

    // 绑定组件变量, 为监听页面滚动
    setFilteredDataRef (ref) {
        this.filteredDataRef = ref;
    }
    // 监听页面滚动，到底后，再次自动加载作品
    handleOnScroll () {
        if (this.filteredDataRef) {
            const contentScrollTop = this.filteredDataRef.scrollTop; // 滚动条距离顶部
            const clientHeight = this.filteredDataRef.clientHeight; // 可视区域
            const scrollHeight = this.filteredDataRef.scrollHeight; // 滚动条内容的总高度
            if ((contentScrollTop > 0) && ((contentScrollTop + clientHeight) >= scrollHeight)) {
                if (!this.state.isOver) {
                    this.getItemList(false); // 继续获取数据的方法
                }
                // console.error('已到底');
            }
        }
    }
    // 手动点击按钮，继续获取数据的方法
    handleGetMoreItem () {
        if (!this.state.isOver) {
            this.getItemList(false);
        }
    }

    // 打开作品
    handleItemSelect (projectId) {
        const newHash = '#' + projectId;
        if (window.location.hash == newHash){
            this.handleClose();
        } else {
            window.location.hash = newHash;
            history.pushState('', '', window.location.pathname + newHash);
        }
    }

    render () {
        return (
            <Modal
                fullScreen
                contentLabel="优秀作品"
                id="ProjectLibrary"
                onRequestClose={this.handleClose}
            >
                <div
                    className={classNames(styles.libraryScrollGrid, styles.withFilterBar)}
                    ref={this.setFilteredDataRef}
                    onScrollCapture={this.handleOnScroll}
                >
                    {this.state.loading ? (
                        <div className={styles.spinnerWrapper}>
                            <Spinner
                                large
                                level="primary"
                            />
                        </div>
                    ) : (<>
                        {(this.state.projects.length == 0) && (
                            <div className={styles.spinnerWrapper}>
                                <div className={styles.spanBox}>空</div>
                            </div>
                        )}

                        {this.state.projects.map((item, index) => (
                            <Card
                                hoverable
                                className={styles.ItemCard}
                                style={{width: 200, margin: 6, borderRadius: 6}}
                                cover={<img src={`/scratch_slt/${item.id}`} style={{width: 180, margin: 10}}/>}
                                key={index}
                                onClick={()=>this.handleItemSelect(item.id)}
                            >
                                <Meta
                                    title={item.title}
                                    description={'热度：'+item.view_count}
                                />
                                <div style={{marginTop: 12}}>
                                    <img alt="头像" src={`/user/${item.authorid}.png`} style={{ width: 20, height: 20, borderRadius: '50%', marginRight: 2}}/>
                                    <span style={{color: '#AAA', fontSize: 8}}>{item.nickname}</span>
                                </div>
                            </Card>
                        ))}

                        {!this.state.isOver && (
                            <div
                                className={styles.spinnerWrapper1}
                                onClick={this.handleGetMoreItem}
                            >
                                <div className={styles.spanBox}>点我可继续</div>
                            </div>
                        )}
                    </>)}
                </div>
            </Modal>
        );
    }
}

ProjectLibrary_yx.propTypes = {
    onRequestClose: PropTypes.func
};

export default ProjectLibrary_yx;
